//
//  TLReadPage.m
//  Books
//
//  Created by tao故乡的云 on 2017/3/18.
//  Copyright © 2017年 故乡的云. All rights reserved.
//

#import "TLReadPage.h"
#import "TLChengYu.h"
#import "TLChengYuPageView.h"
#import "TLPopMenu.h"
#import "TLPopMenuItem.h"
#import "TLBottomBar.h"

@interface TLReadPage ()<TLPopMenDelegate,TLBottomBarDelegate>
@property(strong, nonatomic) TLChengYuPageView *showView;
@property(strong, nonatomic) TLChengYuPageView *hideView;
@property(strong, nonatomic) TLChengYuPageView *cacheView;
@property(weak, nonatomic) TLPopMenu *popView;
@property(weak, nonatomic) TLBottomBar *bottomBar;
@property(strong, nonatomic) NSMutableArray *historyItems;
@property(strong, nonatomic) NSMutableArray *loves;
@end

@implementation TLReadPage
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    // 转场触发手势
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
    [self.view addGestureRecognizer:pan];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_more_normal"] style:UIBarButtonItemStylePlain target:self action:@selector(popMenu)];
    self.bottomBar = [TLBottomBar show];
    self.bottomBar.delegate = self;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 保存数据到沙盒
    NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
   
    NSString *path = [cachePath stringByAppendingPathComponent:@"historyItems.plist"];
    [NSKeyedArchiver archiveRootObject:self.historyItems toFile:path];
    
    NSString *path1 = [cachePath stringByAppendingPathComponent:@"loves.plist"];
    [NSKeyedArchiver archiveRootObject:self.loves toFile:path1];
//    if(self.type == TLReadPageTypeLove) {
//
//    }else if(self.type == TLReadPageTypeDefault) {
////        NSString *path = [cachePath stringByAppendingPathComponent:@"cyLexicon.plist"];
////        数据处理，后再存
//    }
    
    [TLBottomBar hidden];
}

- (void)popMenu {
    if (self.popView.hidden == NO) {
        [UIView animateWithDuration:0.8 animations:^{
            self.popView.alpha = 0.01;
        } completion:^(BOOL finished) {
            self.popView.hidden = YES;
            self.popView.alpha = 1.0;
        }];
        
    }else {
        self.popView.hidden = NO;
    }
}

#pragma mark - TLPopMenDelegate
- (void)popMenu:(TLPopMenu *)popMenu didSelectItemAtIndex:(NSInteger)index {
    NSLog(@"----item  --  %li",index);
}

- (void)popMenuDismiss:(TLPopMenu *)popMenu {
    if (self.popView.hidden == NO) {
        [UIView animateWithDuration:0.8 animations:^{
            self.popView.alpha = 0.01;
        } completion:^(BOOL finished) {
            self.popView.hidden = YES;
            self.popView.alpha = 1.0;
        }];
        
    }else {
        self.popView.hidden = NO;
    }
}

#pragma mark - Bottom bar Delegate
- (void)bottomBar:(TLBottomBar *)view didClickDeleteButton:(UIButton *)btn {
    
}

- (void)bottomBar:(TLBottomBar *)view didClickLoveButton:(UIButton *)btn {
    _bottomBar.loveSelected = !_bottomBar.loveSelected;
    self.showView.chengYu.love =  _bottomBar.loveSelected;
    
    TLChengYu *cy = [self.items objectAtIndex:self.currentItem];
    bool have = NO;
    for (TLChengYu *item in self.loves) {
        
        have = [item.name isEqualToString:cy.name];
        if (have) {
            [self.loves removeObject:item];
            break;
        }
    }
    if (!have) [self.loves insertObject:cy atIndex:0];
    
}

- (void)bottomBar:(TLBottomBar *)view didClickEditButton:(UIButton *)btn {
    
}

#pragma mark - 手势
#define kSpace 0.3  // 手指滑过屏幕kSpace倍及以上时触发转场动画
- (void)pan:(UIPanGestureRecognizer *)pan {
    if (!self.popView.hidden) return; // popMenu 显示中，屏蔽翻页手势
    
    static CGFloat x1 = 0.0;
    if (pan.state == UIGestureRecognizerStateBegan) {
        x1 = [pan locationInView:self.view].x;
        
    }else if(pan.state == UIGestureRecognizerStateChanged) {
        CGFloat x2 = [pan locationInView:self.view].x;
        self.showView.transform = CGAffineTransformMakeTranslation(x2 - x1, 0);
        
    }else if(pan.state == UIGestureRecognizerStateEnded) {
        CGFloat space = [pan locationInView:self.view].x - x1;
        
        
        if (space >= self.view.bounds.size.width * kSpace) { // 上一组
            [self viewTransform:NO];
//            NSLog(@"上一组");
        }else if(ABS(space) >= self.view.bounds.size.width * kSpace) { // 下一组
            [self viewTransform:YES];
//            NSLog(@"下一组");
        }else {
            // 转场触发失败，恢复原状
            [UIView animateWithDuration:0.4 animations:^{
                
                self.showView.transform = CGAffineTransformIdentity;
            }];
        }
    }
}

#define kDuration 0.2  // 转场动画时间
- (void)viewTransform:(BOOL)isNext {
    self.cacheView = self.showView;
    self.showView = self.hideView;
    self.hideView = self.cacheView;
    
    if (isNext) {
        if (self.currentItem == self.items.count - 1) {
            self.currentItem = 0;
        }else {
            self.currentItem++;
        }
        [UIView animateWithDuration:kDuration animations:^{
            self.hideView.transform = CGAffineTransformMakeTranslation(-self.view.bounds.size.width, 0);
        } completion:^(BOOL finished) {
            [self.showView removeFromSuperview];
            [self.view insertSubview:self.showView aboveSubview:self.hideView];
            self.hideView.transform = CGAffineTransformIdentity;
        }];
        
    }else {
        if(self.currentItem == 0) {
            self.currentItem = self.items.count -1;
        }else {
            self.currentItem--;
        }
        [UIView animateWithDuration:kDuration animations:^{
            self.hideView.transform = CGAffineTransformMakeTranslation(self.view.bounds.size.width, 0);
        } completion:^(BOOL finished) {
            [self.showView removeFromSuperview];
            [self.view insertSubview:self.showView aboveSubview:self.hideView];
            self.hideView.transform = CGAffineTransformIdentity;
        }];
    }
}

#pragma mark - properties

- (void)setType:(TLReadPageType)type {
    _type = type;
    if (type == TLReadPageTypeDefault) {
        self.bottomBar.deleteEnabe = NO;
    }else {
        self.bottomBar.deleteEnabe = YES;
    }
}

- (NSMutableArray *)historyItems {
    if (_historyItems == nil) {
        NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
        NSString *path = [cachePath stringByAppendingPathComponent:@"historyItems.plist"];
        _historyItems = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        if (_historyItems == nil) {
            _historyItems = [NSMutableArray array];
        }
    }
    
    return _historyItems;
}

- (NSMutableArray *)loves {
    if (_loves == nil) {
        NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
        NSString *path = [cachePath stringByAppendingPathComponent:@"loves.plist"];
        _loves = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        if (_loves == nil) {
            _loves = [NSMutableArray array];
        }
    }
    
    return _loves;
}

- (TLPopMenu *)popView {
    if (_popView == nil) {
        TLPopMenu *popView = [[TLPopMenu alloc] initWithFrame:self.view.bounds];
        self.popView = popView;
        [self.view addSubview:popView];
        self.popView.hidden = YES;
        popView.delegate = self;
        NSMutableArray *items = [NSMutableArray array];
        for (int i = 0; i < 4; i++) {
            TLPopMenuItem *item = [[TLPopMenuItem alloc] init];
            item.icon = [UIImage imageNamed:@"tabbar_discover_highlighted"];
            item.title = @"item";
            [items addObject:item];
        }
        
        self.popView.items = items;
    }
    
    return _popView;
}


- (void)setItems:(NSArray *)items {
    _items = [NSArray arrayWithArray:items];
}

- (TLChengYuPageView *)showView {
    if (_showView == nil) {
        _showView = [TLChengYuPageView shengYuPageView];
        //        _showView.backgroundColor = [UIColor colorWithRed:0.5 green:0.4 blue:0.3 alpha:1];;
        _showView.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height  - 44);
        [self.view addSubview:_showView];
    }
    
    return _showView;
}

- (TLChengYuPageView *)hideView {
    if (_hideView == nil) {
        _hideView = [TLChengYuPageView shengYuPageView];
        //        _hideView.backgroundColor = [UIColor colorWithRed:0.5 green:0.4 blue:0.3 alpha:1];
        _hideView.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - 44);
        
        [self.view addSubview:_hideView];
    }
    
    return _hideView;
}

- (void)setCurrentItem:(NSInteger)currentItem {
    _currentItem = currentItem;
    TLChengYu *cy = [self.items objectAtIndex:currentItem];
    self.showView.chengYu = cy;
    self.navigationItem.title = cy.name;
    self.bottomBar.loveSelected = cy.isLove;
    
    bool have = NO;
    for (TLChengYu *item in self.historyItems) {
        have = [item.name isEqualToString:cy.name];
        if (have) break;
    }
    if (have) return;
    [self.historyItems insertObject:cy atIndex:0];
}
@end
